package com.baseweb.webadmin.validation;


import com.baseweb.webadmin.core.model.bvo.UserForm;
import com.baseweb.webadmin.core.util.HTMLFilter;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;

public class LoginValidator {
    public void validate(UserForm userForm, String checkCode, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "validation.required", "用户名不能为空");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "validation.required", "密码不能为空");

        //check xss
        HTMLFilter filter = new HTMLFilter();
        String name = userForm.getUsername();
        String pwd = userForm.getPassword();
        if (!name.equalsIgnoreCase(filter.filter(name))) {
            errors.rejectValue("username", "validation.error", "用户名错误");
        }
        if (!pwd.equalsIgnoreCase(filter.filter(pwd))) {
            errors.rejectValue("password", "validation.error", "密码错误");
        }

        if (userForm != null && userForm.getCheckCode() != null && checkCode != null && !"".equals(checkCode)) {
            String inputCheckCode = userForm.getCheckCode().toLowerCase();
            if (inputCheckCode.length() != 4 || !checkCode.equals(inputCheckCode)) {
                errors.rejectValue("checkCode", "validation.checkCode.invalid", "验证码错误");
            }
        } else {
            errors.rejectValue("checkCode", "validation.checkCode.invalid", "验证码错误");
        }
    }
}
